﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace mqtt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        MqttClient client;

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建客户端实例  
            client = new MqttClient(IPAddress.Parse("111.231.134.109")); //主机为IP时  
            //MqttClient client = new MqttClient(MQTT_BROKER_ADDRESS); //当主机地址为域名时  

            // 注册消息接收处理事件，还可以注册消息订阅成功、取消订阅成功、与服务器断开等事件处理函数  
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

            //生成客户端ID并连接服务器  
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            client.Subscribe(new string[] { "ip" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }

        void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            //处理接收到的消息  
            string msg = System.Text.Encoding.UTF8.GetString(e.Message);
            textBox1.AppendText("收到消息:" + msg + "\r\n");

            SaveFileDialog sfd = new SaveFileDialog();
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            // 发布消息到主题 "/home/temperature" 消息质量为 2,不保留   
            client.Publish("getip", Encoding.UTF8.GetBytes(" "), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            client.Disconnect();
        }

        private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            textBox1.Clear();
        }
    }
}
